//author:jxx
//此处是对表单的方法，组件，权限操作按钮等进行任意扩展(方法扩展可参照SellOrder.js)
let extension = {
  components: {
    //动态扩充组件或组件路径
    //表单header、content、footer对应位置扩充的组件
    gridHeader: () => import("./producttext.vue"), //{ template: "<div>扩展组xx件</div>" },
    gridBody: () => import("../../views/product/productsBox.vue"),
    gridFooter: "",
    //选择属性弹出框
    modelHeader: () => import("../mall/product/Product_Attr.vue"),
    modelBody: "",
    modelFooter: ""
  },
  data () {
    return {
      list: [],
      detailData: [],
      zqnum: [],
      zqAccount: [],
      zqList: [],
      kaAccount: [],
      kaList: [],
      CampData: [],
      CampDataAdd: [],
      CampsiteHouseList: [],
      houseTypeList: [],
      cinemascList: [],
      procureProductArrData: []
    };
  },
  // buttons: { view: [
  //   {
  //     name: "拉取",
  //     icon: "md-add",
  //     value: "Pull",
  //     class: "",
  //     type: "error",
  //     index: 4,
  //     onClick: function () {
  //       this.$refs.gridBody.open()
  //     }
  //   },
  // ], box: [], detail: [] }, //扩展的按钮
  methods: {
    //事件扩展
    // 循环表单并返回数据
    getFormOption (field) {
      let option;
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        });
      });
      return option;
    },
    getDetailColumns (field) {
      let option;
      this.detail.columns.forEach(item => {
        if (item.field == field) {
          option = item;
        }
      });
      return option;
    },
    onInit () {
      this.const.PAGE = 'getPageData'
      //点击单元格编辑与结束编辑(默认是点击单元格编辑，鼠标离开结束编辑)
      this.searchFormFields.effectiveState = "0";
      this.detailOptions.clickEdit = true;
      // label宽度
      //this.boxOptions.labelWidth = 100
      // 弹框宽度
      this.boxOptions.width = 1000;
      // 开启单选
      ////;
      // 内容超出后自动换行
      this.textInline = true;
      // let houseType = this.getDetailColumns('houseType')
      this.http
        .post("/api/Dictionary/GetVueDictionary", [
          "Campsite_Name",
          "Campsite_Name_Add",
          "CampsiteHouse",
          "houseType",
          "getScreenName"
        ])
        .then(res => {
          res.forEach(i => {
            if (i.dicNo == "Campsite_Name") {
              this.CampData = i.data;
            } else if (i.dicNo == "Campsite_Name_Add") {
              this.CampDataAdd = i.data;
            } else if (i.dicNo == "houseType") {
              // houseType.bind.data = i.data
            } else if (i.dicNo == "CampsiteHouse") {
              this.CampsiteHouseList = i.data;
            } else if (i.dicNo == "getScreenName") {
              this.cinemascList = i.data
            }
          });
        });
      let params = {
        page: 1,
        rows: 500,
        sort: "id",
        order: "desc",
        wheres: "[]"
      };
      this.http.post("/api/MebCoupon/CouponGetPageData", params).then(res => {
        this.zqAccount = res.rows.map(i => {
          return {
            key: i.code,
            value: i.name
          };
        });
      });

      // 卡模板
      this.http.post("/api/MebCardtype/CardGetPageData", params).then(res => {
        this.kaAccount = res.rows.map(i => {
          return {
            key: i.cardtypeid.toString(),
            value: i.cardtypename
          };
        });
      });


      // //    循环表单
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          let field = item.field;
          // 给酒店名称（酒店ID）绑定change事件

          if (field == "hotel_ID") {
            item.onChange = (key, ele) => {
              this.$refs.detail.reset(); //清空从表
              // 新建时 选择酒店名称 调取 酒店房型接口
              if (this.currentAction == "Add" && key) {
                if (this.editFormFileds.name == "") {
                  this.$Message.error("请先填写产品名称");
                } else if (this.editFormFileds.pmsRoomCode == "") {
                  this.$Message.error("请先填写pms房价码");
                } else {
                  let param = {
                    delKeys: null,
                    detailData: null,
                    mainData: {
                      AddGoods: this.editFormFileds.name,
                      hotel_ID: this.editFormFileds.hotel_ID,
                      pmsRoomCode: this.editFormFileds.pmsRoomCode
                    }
                  };
                  this.http
                    .post("/api/Products/AddGoodsHotel", param)
                    .then(res => {
                      if (res.data.length > 0) {
                        // 将酒店房型数据 放到 酒店产品商品上
                        for (let index = 0; index < res.data.length; index++) {
                          let item = res.data[index];
                          this.$refs.detail.addRow(item);
                        }
                      }
                    });
                }
              }
            };
          } else if (field == "supplierCode") {
            item.onChange = (key, ele) => {
              let pointsId = this.getFormOption("pointsId");
              this.http
                .get("/api/SupplierNews/GetPoints", { supplierCode: key }, true)
                .then(res => {
                  if (res.data.length != 0) {
                    pointsId.data = res.data.map(i => {
                      return {
                        key: i.pointsId,
                        value: i.pointsName
                      };
                    });
                  } else {
                    pointsId.data = []
                  }
                });
            };
          } else if (field == "campsiteName") {
            item.onChange = (key, ele) => {
              // 新建时 选择营地名称 调取 营地营期的接口
              if (this.currentAction == "Add") {
                if (this.editFormFields.type[0] == "YingDi") {
                  let params = {
                    order: "desc",
                    page: 1,
                    rows: 100,
                    sort: "createDate",
                    value: key,
                    wheres: "[]"
                  };
                  this.http
                    .post("/api/Campsite/getDetailPage_AllowAnonymous", params, true)
                    .then(result => {
                      if (result.rows) {
                        if (result.rows.length > 0) {
                          //     将营地营期数据 放到 产品商品上
                          this.$refs.detail.reset(); //清空从表
                          for (
                            let index = 0;
                            index < result.rows.length;
                            index++
                          ) {
                            let item = result.rows[index];
                            let record = { name: "", code: "" };
                            record.name = item.phase_name;
                            record.code = item.phase_id_fk;
                            record.spare7 = item.people_num;
                            record.campsitePhaseId = item.phase_id_fk;
                            // 开始时间
                            record.spare10 = item.begin_time;
                            // 结束时间
                            record.spare11 = item.end_time;
                            record.stockTotal = item.stocknum;
                            record.num = item.stocknum;
                            //       record.num = item.real_Quantity
                            record.elementIdex = index;
                            this.$refs.detail.addRow(record);
                          }
                        }
                      }
                    });
                } else {
                  // 营位的单位ID
                  console.log(key, "key");
                  let param = {
                    page: 1,
                    rows: 100000,
                    sort: "createDate",
                    order: "desc",
                    wheres: `[{\"name\":\"id\",\"value\":\"${key}\",\"displayType\":\"checkbox\"}]`
                  };
                  this.http
                    .post("api/CampHouseBase/GetPageData_AllowAnonymous", param)
                    .then(res => {
                      console.log(res.rows[0].campUnitId, "res");
                      this.editFormFileds.campUnitId = res.rows[0].campUnitId
                    });
                  let params = {
                    order: "desc",
                    page: 1,
                    rows: 100,
                    sort: "createDate",
                    value: key,
                    wheres: "[]"
                  };
                  this.http
                    .post("/api/CampHouseBase/getDetailPage_AllowAnonymous", params)
                    .then(result => {
                      if (result.rows) {
                        if (result.rows.length > 0) {
                          this.$refs.detail.reset();
                          for (
                            let index = 0;
                            index < result.rows.length;
                            index++
                          ) {
                            let item = result.rows[index];
                            let record = {};
                            record.name = item.name;
                            record.code = item.id;
                            record.originalPrice = this.editFormFileds.costprice;
                            record.timeContainer = [
                              item.startTime,
                              item.endTime
                            ];
                            record.elementIdex = index;
                            record.houseType = item.houseType;
                            record.spare8 = item.dayNum == 1 ? 1 : 0
                            this.$refs.detail.addRow(record);
                          }
                        }
                      }
                    });
                }
              }
            };
          } else if (field == "regular_bus_id") {
            item.onChange = (key, ele) => {
              // 新建时 选择路线名称 调取 路线时间点的接口
              if (this.currentAction == "Add") {
                this.pointTime(key);
              }
            };
          } else if (field == "venueName") {
            // let venueName = this.getFormOption('venueName')
            // let parm = { "page": 1, "rows": 30, "sort": "venue_id", "order": "desc", "wheres": "[]" }
            // this.http.post('/api/Venue/getPageData', parm).then(res => {
            //   venueName.data = res.rows.map(i => {
            //     return {
            //       key: i.venue_id,
            //       value: i.venueName
            //     }
            //   })
            // })
            console.log(this.editFormFields.venueName, "1111")
            // if(this.editFormFields.venueName!=""){
            let cinemascreenid = this.getFormOption("cinemascreenid"); //场次
            item.onChange = (key, ele) => {
              // 新建时 选择营地名称 调取 营地营期的接口
              if (this.currentAction == "Add") {
                let params = {
                  venueid: key,
                };
                this.http
                  .get("/api/cinemaSeat/GetScreeing", params)
                  .then(result => {
                    cinemascreenid.data = result.data.map(i => {
                      return {
                        key: i.screenid,
                        value: i.screenName
                      }
                    })
                  });
              }
            };
            cinemascreenid.onChange = (r, t) => {
              if (this.currentAction == "Add") {
                this.$refs.detail.reset()
                let df = {
                  screenid: r,
                };
                this.http
                  .get("/api/cinemaSeat/GetSeatGood", df)
                  .then(result => {
                    if (result.data) {
                      if (result.data.length > 0) {
                        result.data.forEach((item, index) => {
                          let obj = {}
                          obj.name = item.name;
                          obj.code = item.screenid;
                          obj.elementIdex = index;
                          obj.originalPrice = ''
                          obj.attributes = null
                          obj.preferentialPrice = ''
                          obj.cinemaseatid = item.cinemaseatid
                          obj.cinemaareaid = item.cinemaareaid
                          obj.cinemavenid = item.cinemavenid
                          this.$refs.detail.addRow(obj);
                        })
                      } else {
                        this.$refs.detail.reset();
                      }
                    }
                  });
              }
            }
            // }
          } else if (field == "tube_code") {
            item.onChange = (key, ele) => {
              this.$refs.detail.reset(); //清空从表
              // 场馆子级接口
              this.http
                .get("/api/Products/GetScreens", { key }, true)
                .then(res => {
                  if (res.status) {
                    res.data.forEach(item => {
                      item.key = item.dicValue;
                      item.value = item.dicName;
                    });
                    let screen_code = this.getFormOption("screen_code"); //场馆子级
                    this.$set(screen_code, "data", res.data);
                    this.$set(screen_code, "disabled", false);
                  } else {
                    this.$Message.error(res.message);
                  }
                });
            };
          } else if (field == "screen_code") {
            item.onChange = (key, ele) => {
              this.$refs.detail.reset(); //清空从表
              // // 新建时 选择场馆子级 调取 商品管理的接口
              if (this.currentAction == "Add") {
                let params = {
                  order: "desc",
                  page: 1,
                  rows: 100,
                  sort: "site_id",
                  value: key,
                  wheres: "[]"
                };
                this.http
                  .post("/api/Screen/GetDetailPage_AllowAnonymous", params, true)
                  .then(result => {
                    if (result.rows) {
                      result.rows.forEach(item => {
                        item.site_code = item.code
                      })
                      this.$refs.detail.rowData.push(...result.rows);
                    }
                  });
              }
            };
          } else if (field == "couponType") {
            this.http
              .post("/api/Dictionary/GetVueDictionary", [
                "mall_productCouponNum"
              ])
              .then(res => {
                this.zqnum = res[0].data;
              });
            let couponcardName = this.getFormOption("couponcardName");
            item.onChange = (key, ele) => {
              switch (key) {
                case "0":
                  couponcardName.data = this.zqAccount;
                  couponcardName.hidden = false;
                  couponcardName.title = "优惠券模板";
                  break;
                case "1":
                  couponcardName.data = this.kaAccount;
                  couponcardName.hidden = false;
                  couponcardName.title = "卡模板";
                  break;
                case "2":
                  couponcardName.hidden = true;
                  break;
              }
            };
          } else if (field == "couponcardName") {
            let couponcardCode = this.getFormOption("couponcardCode");
            item.onChange = (key, ele) => {
              let params = {
                page: 1,
                rows: 500,
                sort: "id",
                order: "desc",
                wheres: "[]"
              };
              if (this.editFormFields.couponType == 0) {
                // 制券信息
                params.wheres = `[{\"name\":\"coupon_code\",\"value\":\"${key}\",\"displayType\":\"text\"}]`;
                this.http
                  .post("/api/MebcouponMake/CouponMakeGetPageData", params)
                  .then(res => {
                    if (res.rows != null && res.rows.length != 0) {
                      couponcardCode.data = res.rows.map(i => {
                        return {
                          key: i.coupon_batch,
                          value: i.coupon_name
                        };
                      });
                    } else {
                      couponcardCode.data = [];
                      this.editFormFields.couponcardCode = "";
                    }
                    couponcardCode.title = "制券列表";
                    couponcardCode.hidden = false;
                  });
              } else if (this.editFormFields.couponType == 1) {
                // 制券信息
                params.wheres = `[{\"name\":\"card_type\",\"value\":\"${key}\",\"displayType\":\"text\"}]`;
                this.http
                  .post("/api/member_card_make/CardMakeGetPageData", params)
                  .then(res => {
                    if (res.rows != null && res.rows.length != 0) {
                      couponcardCode.data = res.rows.map(i => {
                        return {
                          key: i.card_batch,
                          value: i.note
                        };
                      });
                    } else {
                      couponcardCode.data = [];
                      this.editFormFields.couponcardCode = "";
                    }
                    couponcardCode.title = "制卡列表";
                    couponcardCode.hidden = false;
                  });
              } else {
                couponcardCode.hidden = true;
              }
            };
          }
        });
      });
      //缓存当前对象
      this.$store.getters.data().reportPrice = this;

      let costpriceOption = this.getFormOption("costprice"); //成本价
      costpriceOption.onInput = val => {
        this.$refs.detail.rowData.forEach(item => {
          item.originalPrice = val ? val : 0;
        });
      };

      // 控制时间选择范围
      // let effectiveStartDate = this.getFormOption('effectiveStartDate');
      // let effectiveEndDate = this.getFormOption('effectiveEndDate');
      // effectiveStartDate.onChange = (val, item) => {
      //     effectiveEndDate.min = val;
      // }
      // effectiveEndDate.onChange = (val, item) => {
      //     effectiveStartDate.max = val;
      // }

      let isInvoicing = this.getFormOption('isInvoicing');
      let receiptInformation = this.getFormOption('receiptInformation');
      let taxRate = this.getFormOption('taxRate');
      isInvoicing.onChange = (val) => {
        if (val == 1) {
          receiptInformation.hidden = false
          receiptInformation.required = true
          taxRate.hidden = false
        } else {
          receiptInformation.hidden = true
          receiptInformation.required = false
          taxRate.hidden = true;
        }
      }

    },
    GetCampHouse (e) {
      let p = new Promise((resolve, reject) => {
        let parma = {
          type: e
        };
        this.http.get("/api/CampHouseBase/GetCampHouse", parma).then((res) => {
          let data = res.data.map((i) => {
            return {
              key: i.id,
              value: i.name,
            };
          });
          resolve(data);
        });
      })
      return p
    },
    GetCamp (e) {
      let p = new Promise((resolve, reject) => {
        let parma = {
          type: e
        };
        this.http.get("/api/Campsite/GetCamp", parma).then((res) => {
          let data = res.data.map((i) => {
            return {
              key: i.campsite_id_fk,
              value: i.campsite_name,
            };
          });
          resolve(data);
        });
      })
      return p
    },
    onInited () {
      //供应商名称
      this.detailOptions.buttons[0].onClick = () => {
        if (this.editFormFields.name == "") {
          this.$Message.error("名称必填");
        } else {
          let params = {
            delKeys: null,
            detailData: null,
            mainData: {}
          };

          let AddGoods = this.editFormFileds.name;
          if (this.editFormFileds.type[0] == "JiuDian") {
            let hotel_ID = this.editFormFileds.hotel_ID;
            let pmsRoomCode = this.editFormFileds.pmsRoomCode;
            params.mainData = {
              ...params.mainData,
              AddGoods,
              hotel_ID,
              pmsRoomCode
            };
          } else {
            params.mainData = { ...params.mainData, AddGoods };
          }
          // debugger
          this.http.post("/api/Products/AddGoods", params).then(res => {
            if (res.status) {
              res.data.forEach(item => {
                item.originalPrice = this.editFormFileds.costprice
                  ? this.editFormFileds.costprice
                  : 0;
                // 2023.11.16改
                // 编辑时新增商品编码自动生成的有问题，赋值为null
                // 编辑的时候点新增会传一个编码到后端  编辑的时候生成编码的判断条件是 如果有编码直接跳过不生成  没编码的行会生成新的
                item.code = null
              });
              if (typeof val === "undefined") {
                // this.$refs.detail.reset();
                this.$refs.detail.rowData.push(...res.data);
              } else if (val == "TaoPiao") {
                this.$refs.modelFooter.tableData = [];
                this.$refs.modelFooter.tableData.push(...res.data);
              }
              //  this.$refs.detail.addRow(res.data);
              // that.$refs.detail.$refs.table = res.data;
              this.model.box2 = false;
              // this.$refs.myform.reset();
            }
          });
        }
        return true;
      };
      this.detailOptions.beginEdit = (row, column, index) => {
        if (row.stockTotal == undefined) {
          row.stockTotal = 0;
        }

        return true; //返回false不会进行编辑
      };
      this.detailOptions.endEditBefore = (row, column, index) => {
        if (row.stockTotal < 0) {
          this.$Message.error("商品总库存不能小于是0");
          row.stockTotal = 0;
        }
        return true;
      };
    },
    searchBefore (param) {
      let wheres = [{
        name: "isDelete",
        value: "0",
        displayType: "text"
      },
      { "name": "proauditStatus", "value": "1", "displayType": "text" }
      ];
      param.wheres.push(...wheres);
      return true;
    },
    // 产品类型 选择对应的修改
    changeType (val) {
      //  控制选择属性的显隐
      this.isAttribute(val);
      // 控制字段显隐
      this.isHidden(val);
      // 控制从表展示字段
      this.isDetail(val);
    },
    //  控制选择属性的显隐
    isAttribute (val) {
      //  酒店 影院 场馆 营地 时 隐藏 其他均为显示
      let selectOption = this.getFormOption("type"); //产品类型
      let campsiteName = this.getFormOption("campsiteName"); //营地
      let supplierProcure = this.getFormOption('supplierProcure')

      if (
        val == "YingDi" ||
        val == "ChangGuan" ||
        val == "YingFang"
      ) {
        selectOption.extra = {};
        if (val == "YingDi") {
          if (this.currentAction == "Add") {
            this.GetCamp(0).then(res => {
              campsiteName.data = res
            })
          } else {
            this.GetCamp(1).then(res => {
              campsiteName.data = res
            })
          }
        } else if (val == "YingFang") {
          if (this.currentAction == "Add") {
            this.GetCampHouse(0).then(res => {
              campsiteName.data = res
            })
          } else {
            this.GetCampHouse(1).then(res => {
              campsiteName.data = res
            })
          }
        }
      } else {
        // 创建选择属性按钮
        selectOption.extra = {
          icon: "ios-search", //显示图表
          text: "选择属性", //显示文本
          style: "color:green;", //指定样式
          click: item => {
            //触发事件
            if (this.editFormFileds.type.length > 0) {
              if (val == "JiuDian") {
                if (this.editFormFileds.name && this.editFormFileds.hotel_ID) {
                  this.$refs.modelHeader.open();
                } else {
                  this.$Message.error("请先填写产品名称、酒店");
                }
              } else if (val == "BanChe0153") {
                if (
                  this.editFormFileds.name &&
                  this.editFormFileds.regular_bus_id
                ) {
                  this.$refs.modelHeader.open();
                } else {
                  this.$Message.error("请先填写产品名称,路线");
                }
              } else if (val === "YingYuan") {
                if (!this.editFormFileds.name) {
                  this.$Message.error("请先填写产品名称");
                  return;
                }
                if (!this.editFormFileds.supplierCode) {
                  this.$Message.error("请先选择供应商");
                  return;
                }
                this.$refs.modelHeader.open();
              }
              else {
                if (this.editFormFileds.name) {
                  this.$refs.modelHeader.open();
                } else {
                  this.$Message.error("请先填写产品名称");
                }
              }
            } else {
              this.$Message.error("请先选择产品类型");
            }
          }
        };
      }
      if (val == "YingDi" || val == "YingFang" || val == 'PiaoKuLeiXing0296') {
        this.detailOptions.buttons.forEach(i => {
          i.icon = "";
          i.name = "";
        });
      } else {
        this.detailOptions.buttons.forEach((i, ii) => {
          if (ii == 0) {
            i.icon = "md-add";
            i.name = "添加行";
          } else if (ii == 1) {
            i.icon = "md-close";
            i.name = "删除行";
          } else if (ii == 2) {
            i.icon = "md-refresh";
            i.name = "刷新";
          }
        });
      }
      // 票库类型
      if (val == 'PiaoKuLeiXing0296') {
        supplierProcure.hidden = false
        if (this.currentAction == "Add") {
          supplierProcure.disabled = false
        } else {
          supplierProcure.disabled = true
        }
        this.http
          .get("api/Mall_procure_task/GetProcureSupplier")
          .then(res => {
            this.$refs.detail.reset();
            if (res.data.length) {
              supplierProcure.data = res.data.map(i => {
                return {
                  value: i.distributorName,
                  key: i.distributorCode
                }
              })
              if (this.currentAction == "Add") {
                supplierProcure.onChange = (key, ele) => {
                  this.http
                    .get("api/Mall_procure_task/GetProcureGoods", { supplierCode: key }, true)
                    .then(res => {

                      if (res.data.length) {
                        this.$refs.detail.rowData = res.data.map(i => {
                          return {
                            ...i,
                            name: i.goods_name,
                          }
                        });
                      }
                    });
                }
              }
            }
          });
      } else {
        supplierProcure.hidden = true
      }
    },
    // 清空 可选属性的值
    clearValue () {
      this.editFormFileds.teachingGrade = "";
      this.editFormFileds.teachingTime = 0;
      // this.editFormFileds.stockTotal = 0;
      this.editFormFileds.hotel_ID = "";
      this.editFormFileds.pmsRoomCode = "";
      this.editFormFileds.campsiteName = "";
      this.editFormFileds.regular_bus_id = "";
      this.editFormFileds.couponType = "";
      this.editFormFileds.couponcardCode = "";
      this.editFormFileds.couponcardName = "";
      this.editFormFileds.venueName = "";
      this.editFormFileds.tube_code = "";
      this.editFormFileds.screen_code = "";
    },
    // 控制字段显隐
    isHidden (val) {
      // console.log("val", val);
      // KeCheng  课程：教学等级 teachingGrade 教学时长 teachingTime 显示且必填
      // JiuDian  酒店：酒店 hotel_ID pms房价码 pmsRoomCode 显示且必填
      // YingDi  营地：营地 campsiteName 显示且必填
      // YingYuan  影院：影院 venueName 显示且必填
      // ChangGuan  场馆：场馆 tube_code 显示且必填
      // 其他：隐藏 所有可选属性
      let teachingGrade = this.getFormOption("teachingGrade"); //教学等级
      let teachingTime = this.getFormOption("teachingTime"); //教学时长
      let hotel_ID = this.getFormOption("hotel_ID"); //酒店名称
      let pmsRoomCode = this.getFormOption("pmsRoomCode"); //pms房价码
      let campsiteName = this.getFormOption("campsiteName"); //营地
      let regular_bus_id = this.getFormOption("regular_bus_id"); //路线
      let couponType = this.getFormOption("couponType"); //账户类型
      let couponcardCode = this.getFormOption("couponcardCode"); //制券列表
      let couponcardName = this.getFormOption("couponcardName"); //制券列表
      let venueName = this.getFormOption("venueName"); //影院
      let cinemascreenid = this.getFormOption("cinemascreenid"); //影院
      let tube_code = this.getFormOption("tube_code"); //场馆
      let screen_code = this.getFormOption("screen_code"); //场馆子级
      let deposit = this.getFormOption("deposit"); //押金
      let restaurant_ID = this.getFormOption("restaurant_ID"); //餐厅名称
      // 控制必填
      this.$set(teachingGrade, "required", val == "KeCheng" ? true : false);
      this.$set(teachingTime, "required", val == "KeCheng" ? true : false);
      this.$set(hotel_ID, "required", val == "JiuDian" ? true : false);
      this.$set(pmsRoomCode, "required", val == "JiuDian" ? true : false);
      this.$set(
        campsiteName,
        "required",
        val == "YingDi" || val == "YingFang" ? true : false
      );
      this.$set(regular_bus_id, "required", val == "BanChe0153" ? true : false);
      this.$set(couponType, "required", val == "Huiyuan" ? true : false);
      // this.$set(couponcardCode, "required", val == "Huiyuan" ? true : false)
      // this.$set(couponcardName, "required", val == "Huiyuan" ? true : false)
      // this.$set(venueName, "required", val == "YingYuan" ? true : false);
      // this.$set(cinemascreenid, "required", val == "YingYuan" ? true : false);
      this.$set(tube_code, "required", val == "ChangGuan" ? true : false);
      this.$set(screen_code, "required", val == "ChangGuan" ? true : false);
      this.$set(restaurant_ID, "required", val == "CanYin" ? true : false);
      // 控制显隐
      this.$set(teachingGrade, "hidden", val == "KeCheng" ? false : true);
      this.$set(teachingTime, "hidden", val == "KeCheng" ? false : true);
      this.$set(hotel_ID, "hidden", val == "JiuDian" ? false : true);
      this.$set(pmsRoomCode, "hidden", val == "JiuDian" ? false : true);
      this.$set(
        campsiteName,
        "hidden",
        val == "YingDi" || val == "YingFang" ? false : true
      );
      this.$set(campsiteName, "title", val == "YingDi" ? "营地" : "营房");
      this.$set(regular_bus_id, "hidden", val == "BanChe0153" ? false : true);
      this.$set(couponType, "hidden", val == "Huiyuan" ? false : true);
      this.$set(couponcardCode, "hidden", val == "Huiyuan" ? false : true);
      this.$set(couponcardName, "hidden", val == "Huiyuan" ? false : true);
      // this.$set(venueName, "hidden", val == "YingYuan" ? false : true);
      // this.$set(cinemascreenid, "hidden", val == "YingYuan" ? false : true);
      this.$set(tube_code, "hidden", val == "ChangGuan" ? false : true);
      this.$set(screen_code, "hidden", val == "ChangGuan" ? false : true);
      this.$set(deposit, "hidden", val == "CanYin" ? true : false);
      this.$set(restaurant_ID, "hidden", val == "CanYin" ? false : true);
      //控制只读
      this.$set(screen_code, "disabled", true);
    },

    // 控制从表展示字段
    isDetail (val) {
      // 酒店、营地：数量 num 显示
      // 酒店、营地、影院、场馆 门市价 originalPrice 优惠价 preferentialPrice
      // 课程、其余：门市价 originalPrice 优惠价 preferentialPrice
      let isEDIT = this.currentAction == this.const.EDIT;
      this.detail.columns.forEach(item => {
        let field = item.field;
        if (isEDIT) {
          if (field == "code") {
            item.hidden = false;
          }
        }

        if (field == "num") {
          item.hidden = val == "YingDi" ? false : true;
        }
        // if (field == "code") {
        //   item.hidden = val == "YingDi" ? true : false
        // }
        if (field == "originalPrice" || field == "preferentialPrice") {
          item.hidden =
            val == "JiuDian" ||
              val == "YingDi" ||
              // val == "YingYuan" ||
              val == "ChangGuan"
              ? true
              : false;
        }
        // if (field == "offlineCode") {
        //   item.hidden = val == "JiuDian" ? true : false;
        // }
        if (field == "spare15" || field == "spare14" || field == 'breakfast_count') {
          item.hidden = val == "JiuDian" ? false : true;
        }
        if (field == "regular_bus_detail") {
          // console.log("===regular_bus_detail")
          item.hidden = val == "BanChe0153" ? false : true;
        }

        if (field == "stockTotal") {
          item.title = val == "JiuDian" ? "商品库存" : "总库存";
        }
        if (field == "houseType" || field == "timeContainer" || field == 'spare8') {
          item.hidden = val == "YingFang" ? false : true;
        }
        if (field == "attributes") {
          item.hidden = val == "YingFang" ? true : false;
          item.hidden = val == "YingYuan" ? true : false;
        }

      });
    },
    // 是否禁止编辑 可选值的属性
    isBanAttribute () {
      // 弹出框是新建还是编辑 isEDIT  true 为编辑 false 为新建
      let isEDIT = this.currentAction == this.const.EDIT;
      let selectOption = this.getFormOption("type"); //产品类型
      let typename = this.getFormOption("typename"); //产品类型名称
      let supplierCode = this.getFormOption("supplierCode"); //供应商
      let supplierName = this.getFormOption("supplierName"); //供应商名称
      let hotel_ID = this.getFormOption("hotel_ID"); //酒店
      let pmsRoomCode = this.getFormOption("pmsRoomCode"); //pms房价码
      let campsiteName = this.getFormOption("campsiteName"); //营地
      let regular_bus_id = this.getFormOption("regular_bus_id"); //路线

      let couponType = this.getFormOption("couponType"); //账户类型
      let couponcardCode = this.getFormOption("couponcardCode"); //制券列表
      let couponcardName = this.getFormOption("couponcardName"); //制券列表
      let venueName = this.getFormOption("venueName"); //影院
      let cinemascreenid = this.getFormOption("cinemascreenid"); //影院
      let tube_code = this.getFormOption("tube_code"); //场馆
      let screen_code = this.getFormOption("screen_code"); //场馆子级
      let deposit = this.getFormOption("deposit"); //押金
      let restaurant_ID = this.getFormOption("restaurant_ID"); //餐厅名称
      // let tubename = this.getFormOption("tubename");//场馆名称

      // 产品类型、供应商  新建：显示 必填 编辑：隐藏 非必填
      this.$set(selectOption, "required", !isEDIT);
      this.$set(supplierCode, "required", !isEDIT);
      this.$set(selectOption, "hidden", isEDIT);
      this.$set(supplierCode, "hidden", isEDIT);
      // 酒店、营地、影院、场馆、场馆子级 新建时可选  编辑时禁止选择
      this.$set(hotel_ID, "disabled", isEDIT);
      this.$set(campsiteName, "disabled", isEDIT);
      this.$set(regular_bus_id, "disabled", isEDIT);
      this.$set(couponType, "disabled", isEDIT);
      this.$set(couponcardCode, "disabled", isEDIT);
      this.$set(couponcardName, "disabled", isEDIT);
      this.$set(venueName, "disabled", isEDIT);
      this.$set(cinemascreenid, "disabled", isEDIT);
      this.$set(tube_code, "disabled", isEDIT);
      this.$set(screen_code, "disabled", isEDIT);
      // 酒店、pms房价码、营地、影院、场馆、场馆子级  新建时隐藏
      this.$set(hotel_ID, "hidden", true);
      this.$set(pmsRoomCode, "hidden", true);
      this.$set(campsiteName, "hidden", true);
      this.$set(regular_bus_id, "hidden", true);
      this.$set(couponType, "hidden", true);
      this.$set(couponcardCode, "hidden", true);
      this.$set(couponcardName, "hidden", true);
      this.$set(venueName, "hidden", true);
      this.$set(cinemascreenid, "hidden", true);
      this.$set(tube_code, "hidden", true);
      this.$set(screen_code, "hidden", true);
      this.$set(deposit, "hidden", false);
      this.$set(restaurant_ID, "hidden", true);
      // this.$set(tubename, "hidden", true)

      // 产品类型名称、供应商名称   新建时 隐藏 编辑时 显示
      this.$set(typename, "hidden", !isEDIT);
      this.$set(supplierName, "hidden", !isEDIT);
    },
    rowClick ({ row, column, event }) {
      //查询界面table点击行选中当前行
      this.$refs.table.$refs.table.toggleRowSelection(row);
      return true;
    },
    // 点击编辑/新建按钮弹出框后
    modelOpenAfter (row) {
      // 产品类型绑定change事件
      let isEDIT = this.currentAction == this.const.EDIT;
      let receiptInformation = this.getFormOption('receiptInformation')
      let txtidOption = this.getFormOption("txtid"); //图文介绍
      let bookingNotice = this.getFormOption('bookingNotice')
      let taxRate = this.getFormOption('taxRate');
      this.detail.columns.forEach(item => {
        let field = item.field;
        if (field == "code") {
          if (isEDIT) {
            item.hidden = false;
          } else {
            item.hidden = true;
          }
        }
      });
      if (isEDIT) {
        if (row.supplierCode) {
          let pointsId = this.getFormOption("pointsId");
          this.http
            .get("/api/SupplierNews/GetPoints", { supplierCode: row.supplierCode }, true)
            .then(res => {
              if (res.data.length != 0) {
                pointsId.data = res.data.map(i => {
                  return {
                    key: i.pointsId,
                    value: i.pointsName
                  };
                });
                this.editFormFields.pointsId = row.pointsId
              } else {
                pointsId.data = []
              }
            });
        }

      }
      this.list = [];
      let selectOption = this.getFormOption("type"); //产品类型

      this.editFormFileds.stockTotal = 0;

      txtidOption.extra = {
        icon: "ios-add",
        text: "添加详情",
        style: "line-height: 31px;margin-left: 11px;",
        click: (column, row, tableData) => {
          if (this.editFormFields.type.length > 0) {
            this.Addtext();
          } else {
            this.$Message.error("请先选择类型！");
          }
        }
      };
      let txtiddatas = [];
      txtiddatas.push(txtidOption.data);
      selectOption.onChange = (val, ele) => {
        this.$refs.detail.reset(); //清空从表
        this.$refs.modelHeader.reset(); //重置选择属性表单
        // 清空 可选属性的值
        this.clearValue();
        // 产品类型 选择对应的修改
        this.changeType(val[0]);
        if (ele.length == 0) {
          // console.log(txtiddatas)
          txtiddatas.forEach(item => {
            item.forEach(item1 => {
              let items = {};
              items.value = item1.value;
              items.key = item1.key;
              items.remark = item1.remark;
              txtidOption.data.push(items);
            });
          });
          this.editFormFields.txtid = "";
        } else {
          txtidOption.data = [];
          txtiddatas.forEach(item => {
            item.forEach(item1 => {
              if (item1.remark == val[0]) {
                let items = {};
                items.value = item1.value;
                items.key = item1.key;
                items.remark = item1.remark;
                txtidOption.data.push(items);
              }
            });
          });
          this.editFormFields.txtid = "";
        }
      };
      this.boxOptions.height = document.documentElement.clientHeight * 0.8;
      // 是否禁止编辑 可选值的属性
      this.isBanAttribute();

      // 新增 编辑
      if (this.currentAction == "Add") {
        this.editFormFileds.typename = "";
        if (this.$refs.modelHeader) {
          this.$refs.modelHeader.reset();
        }
        receiptInformation.required = false
        this.editFormFileds.isInvoicing = 0
        taxRate.hidden = true
        receiptInformation.hidden = true
        this.editFormFields.receiptInformation = receiptInformation.data[0].key
        this.editFormFields.txtid = txtidOption.data[0].key
        this.editFormFields.bookingNotice = bookingNotice.data[0].key
      } else {
        // 将开始日期 和 结束日期合并为起止日期
        if (row.regular_bus_id != "" && row.regular_bus_id != null) {
          this.pointTime(row.regular_bus_id);
        }

        this.editFormFields.timeContainer = [
          row.effectiveStartDate,
          row.effectiveEndDate
        ];

        this.editFormFileds.stockTotal = row.stockTotal;
        if ((typeof this.editFormFileds.type) != Array) {
          this.editFormFileds.type = row.type
        }
        this.changeType(row.typeParentID);

        this.detailData = [];
        let params = {
          page: 1,
          rows: 100,
          sort: "code",
          order: "desc",
          wheres: "[]",
          value: row.id
        };
        this.http.post("api/Products/getDetailPage", params).then(res => {
          res.rows.forEach(i => {
            // i.timeContainer = i.spare10
            i.timeContainer = [i.spare10, i.spare11];
            i.spare8 = i.spare8 != null ? Number(i.spare8) : 0
            if (row.typeParentID == "YingYuan") {
              i.name = i.name + '(' + i.attributesName + ')'
            };
          });
          this.$refs.detail.rowData = res.rows;
          this.detailData = res.rows;

        })
        if (row.typeParentID == "YingDi") {
          this.detailOptions.edit = false;
        }
        else {
          this.detailOptions.edit = true;
        }
      }
    },
    // 查询时间点
    pointTime (val) {
      let params = {
        order: "desc",
        page: 1,
        rows: 100,
        sort: "createDate",
        value: val,
        wheres: "[]"
      };
      this.http
        .post("/api/Mall_regular_bus/GetDetailPageBus", params, true)
        .then(result => {
          console.log("数据", result);
          var datalist = [];
          if (result.rows) {
            if (result.rows.length > 0) {
              //     将路线的时间点数据 放到 产品商品上
              if (this.currentAction == "Add") {
                this.$refs.detail.reset(); //清空从表
              }
              datalist = result.rows.map(j => {
                return {
                  key: j.id,
                  value: j.startTime
                };
              });
              this.detail.columns.forEach(x => {
                if (x.field == "regular_bus_detail") {
                  x.edit = { type: "selectList" };
                  x.bind = { key: "pointTime", data: datalist };
                }
              });
            }
          }
        });
    },

    modelOpenBefore (row) {
      let campsiteName = this.getFormOption("campsiteName"); //营地
      let cinemascreenid = this.getFormOption("cinemascreenid"); //场次

      if (this.currentAction == "Add") {

        this.detailOptions.buttons.forEach((i, ii) => {
          if (ii == 0) {
            i.icon = "md-add";
            i.name = "添加行";
          } else if (ii == 1) {
            i.icon = "md-close";
            i.name = "删除行";
          } else if (ii == 2) {
            i.icon = "md-refresh";
            i.name = "刷新";
          }
        });
        // getScreenName
        if (this.editFormFields.venueName != "") {
          let params4 = {
            venueid: row.venueName,
          };
          this.http
            .get("/api/cinemaSeat/GetScreeing", params4)
            .then(result => {
              cinemascreenid.data = result.data.map(i => {
                return {
                  key: i.screenid,
                  value: i.screenName
                }
              })
            });
        }
      } else {
        if (row.type == "YingDi") {
          this.GetCamp(1).then(res => {
            campsiteName.data = res
          })
        } else if (row.type == "YingFang") {
          this.GetCampHouse(1).then(res => {
            campsiteName.data = res
          })
        }
        // if (row && row.type && typeof row.type == 'string') {
        //   row.type = row.type.split(',')
        // }
        let couponcardName = this.getFormOption("couponcardName");
        let couponcardCode = this.getFormOption("couponcardCode");
        let params2 = {
          page: 1,
          rows: 500,
          sort: "id",
          order: "desc",
          wheres: "[]"
        };
        if (row.couponType == 0) {
          couponcardName.data = this.zqAccount;
          couponcardName.hidden = false;
          couponcardName.title = "优惠券模板";
          // 制券信息
          params2.wheres = `[{\"name\":\"coupon_code\",\"value\":\"${row.couponcardName}\",\"displayType\":\"text\"}]`;
          this.http
            .post("/api/MebcouponMake/CouponMakeGetPageData", params2)
            .then(res => {
              if (res.rows != null && res.rows.length != 0) {
                couponcardCode.data = res.rows.map(i => {
                  return {
                    key: i.coupon_batch,
                    value: i.coupon_name
                  };
                });
              } else {
                couponcardCode.data = [];
              }
              couponcardCode.title = "制券列表";
              couponcardCode.hidden = false;
            });
        } else if (row.couponType == 1) {
          couponcardName.data = this.kaAccount;
          couponcardName.hidden = false;
          couponcardName.title = "卡模板";
          // 制券信息
          params2.wheres = `[{\"name\":\"card_type\",\"value\":\"${row.couponcardName}\",\"displayType\":\"text\"}]`;
          this.http
            .post("/api/member_card_make/CardMakeGetPageData", params2)
            .then(res => {
              if (res.rows != null && res.rows.length != 0) {
                couponcardCode.data = res.rows.map(i => {
                  return {
                    key: i.card_batch,
                    value: i.note
                  };
                });
              } else {
                couponcardCode.data = [];
              }
              couponcardCode.title = "制卡列表";
              couponcardCode.hidden = false;
            });
        } else {
          couponcardName.hidden = true;
          couponcardCode.hidden = true;
        }
        if (row.typeParentID == "YingDi" || row.typeParentID == "YingFang") {
          this.detailOptions.buttons.forEach(i => {
            i.icon = "";
            i.name = "";
          });
        } else {
          this.detailOptions.buttons.forEach((i, ii) => {
            if (ii == 0) {
              i.icon = "md-add";
              i.name = "添加行";
            } else if (ii == 1) {
              i.icon = "md-close";
              i.name = "删除行";
            } else if (ii == 2) {
              i.icon = "md-refresh";
              i.name = "刷新";
            }
          });
        }
      }
    },
    delDetailRow (rows) {
      // 逻辑删除
      if (this.detailData !== undefined) {
        this.detailData.forEach(k => {
          rows.forEach(i => {
            if (k.goodId == i.goodId) {
              i.isDelete = 1;
              this.list.push(i);
            }
          });
        });
      }
      return true;
    },
    addBefore (formData) {
      //新建保存前formData为对象，包括明细表
      // console.log(formData)
      if (formData.detailData.length != 0) {
        formData.detailData.forEach(i => {
          i.isDelete = 0;
        });
      }

      return this.veriFromTable(formData);
    },
    updateBefore (formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      // console.log(formData,"formData")
      formData.detailData.push(...this.list);
      return this.veriFromTable(formData);
    },
    // 保存前编辑
    veriFromTable (formData) {
      Object.keys(formData.mainData).forEach(_ => {
        formData.mainData[_] = formData.mainData[_] == null ? '' : formData.mainData[_]
      })
      // console.log("保存前编辑", formData.mainData.mainLabel);
      if (formData.mainData.mainLabel == undefined) {
        formData.mainData.mainLabel = "";
      }
      let timeContainer = formData.mainData.timeContainer.split(",");
      if (timeContainer.length > 0 && timeContainer[0] != "") {
        formData.mainData.effectiveStartDate = timeContainer[0];
        formData.mainData.effectiveEndDate = timeContainer[1];
      } else {
        this.$Message.error("请选择有效起止日期！");
      }
      if (formData.mainData.hotel_ID) {
        for (let index = 0; index < formData.detailData.length; index++) {
          const element = formData.detailData[index];
          if (!element.name) {
            this.$Message.error("请输入商品名称！");
            return false;
          }
          // 商品新建有问题，暂时注掉必填，后端要求新建时不传商品编码，编辑时要传，商品编码是后端生成的
          // else if (!element.code) {
          // this.$Message.error("请输入商品编号！");
          // return false;
          // }

          if (this.editFormFileds.type[0] == "JiuDian") {
            if (!element.stockTotal) {
              this.$Message.error("请输入商品库存！");
              return false;
            }
            formData.detailData.forEach(i => {
              i.breakfast_count = i.breakfast_count == undefined ? 0 : i.breakfast_count
            });
          } else {
            if (!element.num) {
              this.$Message.error("请输入商品数量！");
              return false;
            }
          }
        }
        return true;
      } else if (this.editFormFileds.type[0] == "ChangGuan") {
        if (formData.mainData.tube_code) {
          return true;
        } else {
          this.$Message.error("请选择场馆！");
          return false;
        }
      } else if (
        this.editFormFileds.type[0] == "Huiyuan" &&
        formData.mainData.couponType == "0"
      ) {
        // 总库存
        // console.log(this.zqnum.filter(i => { return i.key == this.editFormFields.couponcardCode }));
        let num = this.zqnum.filter(i => {
          return i.key == this.editFormFields.couponcardCode;
        })[0].value;
        if (formData.mainData.stockTotal > num) {
          this.$Message.error("总库存不能大于券的剩余数量");
          return false;
        } else {
          return true;
        }
      } else if (this.editFormFileds.type[0] == "YingFang") {
        formData.detailData.forEach(i => {
          i.spare9 = i.houseType;
          i.spare10 = i.timeContainer[0];
          i.spare11 = i.timeContainer[1];
        });
        return true;
      } else if (this.editFormFileds.type[0] == "YingYuan") {
        formData.detailData.forEach(i => {
          i.name = i.name.split("(")[0]
        });
        return true;
      } else {
        return true;
      }
    },
    Addtext () {
      this.$store.getters.data().addproducttext = this;
      this.$refs.gridHeader.open(this.editFormFields.type);
    },
    submit (res) {
      // console.log('res', res)
      let selectOption = this.getFormOption("txtid"); //产品类型
      // console.log(selectOption.data)
      selectOption.data.push({
        key: res.code,
        value: res.title,
        remark: res.text_Type
      });
      this.editFormFields.txtid = res.code;
    },
    addRow () {
      let obj = {
        name: this.editFormFields.name
      };
      this.detail.columns.forEach(i => {
        if (i.field == "spare15") {
          i.edit = { type: "text" };
        }
      });
      this.$refs.detail.addRow(obj);
    },
    delBefore (ids, rows) {
      let code = rows.map(i => i.code);
      let params = {
        page: 1,
        rows: 30,
        sort: "createDate",
        order: "desc",
        wheres: `[{\"name\":\"productid\",\"value\":\"${code.join(
          ","
        )}\",\"displayType\":\"checkbox\"}]`
      };
      this.http.post("api/distriProducts/getPageData", params).then(res => {
        if (res.rows.length != 0) {
          this.$Message.error("当前产品已被发布，暂时不能删除");
        } else {
          this.$Modal.confirm({
            title: "删除警告!",
            content:
              '<p style="color: red;font-weight: bold;letter-spacing: 3px;">确认要删除选择的数据吗?</p>',
            onOk: () => {
              this.http.post("api/Products/del", ids).then(res => {
                this.$Message.success("删除成功");
                this.refresh();
              });
            }
          });
        }
      });
    }
  }
};
export default extension;
